from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.conf import settings
from nekoTrace.nekonekotrace.dbUpdate import *
import os

def postCatPicView(request):
    try:
        if request.method == 'POST':
            catid = request.POST['catid']
            userid = request.POST['userid']
            file = request.FILES.get('filename','')
            filename = file.name


            fname = os.path.join(settings.MEDIA_ROOT,'catpic/',filename)
            f2name = os.path.join(settings.MEDIA_URL,'catpic/',filename)
            if os.path.exists(fname):
                os.remove(fname)
            dirs = os.path.dirname(fname)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            if os.path.isfile(fname):
                os.remove(fname) 


            fp = open(fname, 'wb')
            for content in file.chunks():
                fp.write(content)

            fp.close()
            
            #update database
            dpNewAlbum(f2name, catid, userid)
            
            return HttpResponse('upload successful')
    except Exception:
        return HttpResponse('upload failed')